package com.csaba.connector.axa;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.csaba.connector.I18NServiceException;
import com.csaba.connector.ServiceException;
import com.csaba.connector.axa.model.AXABank;
import com.csaba.connector.axa.model.AXASession;
import com.csaba.connector.model.Account;
import com.csaba.connector.model.Amount;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractAccountService;

public class AXAAccountService extends AbstractAccountService implements Codes
{

	@Override
	public void execute( final Session session ) throws ServiceException
	{
		if ( !( session instanceof AXASession ) )
			throw new ServiceException("Incompatible session " + AXABank.class + " != " + session.getClass().getName());

		final AXASession axa = (AXASession) session;
		final Account account = (Account) axa.getRemoteProperty(RP_SELECTED_ACCOUNT);

		final NameValuePair[] request = new NameValuePair[] {// 
		new BasicNameValuePair("AccountNumber", account.getNumber()),//
		};

		final String accountBalanceResult = axa.doPost(AXASession.getRequestURL(REQUEST_ACCOUNT_BALANCE), request);

		axa.debugFile("accountBalanceResult", accountBalanceResult);

		//{"__id":0,"OpeningBalance":1234.56,"CurrentBalance":123456.78}
		try
		{
			final JSONObject result = new JSONObject(accountBalanceResult);
			if ( !result.has("OpeningBalance") || !result.has("CurrentBalance") )
			{
				throw AXAUtil.serverError(accountBalanceResult);
			}
			else
			{
				account.setBookedBalance(new Amount(result.getDouble("OpeningBalance"), account.getCurrency()));
				account.setAvailableBalance(new Amount(result.getDouble("CurrentBalance"), account.getCurrency()));
			}
		}
		catch ( final JSONException e )
		{
			throw new I18NServiceException(AXABank.getInstance(), "err.accountBalance", e);
		}

		accounts = new Account[] { account };
	}
}
